#include "paramset.h"
#include "ui_paramset.h"
#include <QMessageBox>
#include <QGraphicsBlurEffect>
#include "msgbox.h"
#include "project.h"
#include "userlogger.h"

ParamSet::ParamSet(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ParamSet)
{
    ui->setupUi(this);
    bdf = BllDataFlow::getInstance();
    sqlHelper = SqlHelper::getInstance();

    //Signals and Slots
    connect(bdf, &BllDataFlow::setWidgetVisibleSignal,this,&ParamSet::setWidgetVisibleSlot);
    connect(bdf, &BllDataFlow::showAllParametersSignal, this, &ParamSet::showAllParametersSlot);
    connect(bdf, &BllDataFlow::retranslateUiSignal, this, &ParamSet::retranslateUiSlot);
    connect(bdf, &BllDataFlow::buildFinishedSignal, this, &ParamSet::setWidgetParent);

    initWidget();

}

ParamSet::~ParamSet()
{
    delete ui;
}

void ParamSet::setWidgetParent()
{
    paramAdd->setParent(Project::Instance());
    paramModify->setParent(Project::Instance());
    paramDelete->setParent(Project::Instance());
}

void ParamSet::on_btnParamAdd_clicked()
{
    paramAdd->clearInput();
    paramAdd->show();
}

void ParamSet::showAllParametersSlot(bool scrollToBottom)
{
    QString table = QString("t_parameter");
    QList<QStringList> info = sqlHelper->selectAllFromTable(table);
    int rowCount = info.size();
    QList<Parameter> paramList;
    for (int i = 0;i < rowCount;i++)
    {
        paramList.append(sqlHelper->convertSL2Parameter(info[i]));
    }

    ui->tableWidget->setRowCount(rowCount);

    for (int i = 0;i < rowCount;i++)
    {
        int rowHeight = 50;
        ui->tableWidget->setRowHeight(i, rowHeight);

        ui->tableWidget->setItem(i, 0, new QTableWidgetItem(paramList[i].name));
        ui->tableWidget->setItem(i, 1, new QTableWidgetItem(paramList[i].code));
        ui->tableWidget->setItem(i, 2, new QTableWidgetItem(QString::number(paramList[i].volt)));
        ui->tableWidget->setItem(i, 3, new QTableWidgetItem(QString::number(paramList[i].pulse)));
        ui->tableWidget->setItem(i, 4, new QTableWidgetItem(QString::number(paramList[i].interval)));
        ui->tableWidget->setItem(i, 5, new QTableWidgetItem(QString::number(paramList[i].speed,'f',2)));
        ui->tableWidget->setItem(i, 6, new QTableWidgetItem(QString::number(paramList[i].times,'f',2)));

        QToolButton * btnUse = new QToolButton(this);
        btnUse->setCheckable(true);
        btnUse->setMaximumWidth(90);
        btnUse->setWhatsThis(paramList[i].name);
        ui->tableWidget->setCellWidget(i, 7, btnUse);
        if (paramList[i].ison)
        {
            btnUse->setStyleSheet(NormalBtnEnableCss);
            btnUse->setText(QString(tr("On")));
        }
        else
        {
            btnUse->setStyleSheet(NormalBtnDisEnableCss);
            btnUse->setText(QString(tr("Off")));
        }

        connect(btnUse,&QToolButton::toggled,this,&ParamSet::checkEnableCountSlot);

        //Operation: Modify, Delete
        QWidget *widget = new QWidget(this);
        QHBoxLayout * horizontalLayout = new QHBoxLayout(widget);
        horizontalLayout->setSpacing(10);
        QToolButton * btnModifyParam = new QToolButton(widget);
        btnModifyParam->setText(QString(tr("Edit")));

        QToolButton * btnDeleteParam = new QToolButton(widget);
        btnDeleteParam->setText(QString(tr("Delete")));
        horizontalLayout->addWidget(btnModifyParam);
        horizontalLayout->addWidget(btnDeleteParam);

        ui->tableWidget->setCellWidget(i, 8, widget);

        QString btnModifyStyleSheet = "QToolButton{border-style:none;color:#00BFFF;border:none;border-image:none;}";
        QString btnDelStyleSheet = "QToolButton{border-style:none;color:#CB0000;border:none;border-image:none;}";
        if (windowWidth >= 1280) {
            btnModifyStyleSheet = "QToolButton{border-style:none;color:#00BFFF;border:none;border-image:none;font-size:20px;}";
            btnDelStyleSheet = "QToolButton{border-style:none;color:#CB0000;border:none;border-image:none;font-size:20px;}";
        }
        btnModifyParam->setStyleSheet(btnModifyStyleSheet);
        btnModifyParam->setWhatsThis(paramList[i].name);
        btnModifyParam->setMaximumWidth(80);
        btnDeleteParam->setStyleSheet(btnDelStyleSheet);
        btnDeleteParam->setWhatsThis(paramList[i].name);
        btnDeleteParam->setMaximumWidth(80);

        connect(btnModifyParam, &QToolButton::clicked, this,&ParamSet::modifyParamSlot);
        connect(btnDeleteParam, &QToolButton::clicked, this,&ParamSet::deleteParamSlot);
    }

    for (int i = 0;i < rowCount;i++) {
        for (int j = 0;j < 7;j++) {
            ui->tableWidget->item(i,j)->setTextAlignment(Qt::AlignCenter);
        }
    }

    if (scrollToBottom)
    {
        ui->tableWidget->scrollToBottom();
    }
}


void ParamSet::checkEnableCountSlot()
{
    //get row number for the selected button
    QToolButton* btnUse = (QToolButton*)sender();
    Parameter p;
    p.name = btnUse->whatsThis();
    QList<Parameter> paramList = sqlHelper->selectParameter(p);
    p = paramList[0];

    EttaError ret;
    QString text;

    //if on, turn it off and update database, set icon to off
    if (p.ison)
    {
        p.ison = false;
        text = tr("Off");
        ret = sqlHelper->updateParameterIson(p);
        if (ret == EttaError::OK)
        {
            btnUse->setStyleSheet(NormalBtnDisEnableCss);
            btnUse->setText(text);
            bdf->loadEnabledParamters();
        }
    }
    else
    {
        //if off, get parameterEnableCount first
        //if less than max limit, turn it on
        QList<QStringList> info = sqlHelper->parameterEnableCount();
        if(info.size() >= MAX_PARAMETER_COUNT)
        {
            MsgBox::information(this, tr("Parameter"), tr("Enable up to %1 parameters").arg(MAX_PARAMETER_COUNT));
            return;
        }

        p.ison = true;
        text = tr("On");
        ret = sqlHelper->updateParameterIson(p);
        if (ret == EttaError::OK)
        {
            btnUse->setStyleSheet(NormalBtnEnableCss);
            btnUse->setText(tr("On"));
            bdf->loadEnabledParamters();
        }
    }

    if (ret == EttaError::OK)
    {
        UserLogger::log(QString(tr("%1 parameter: %2(%3)")).arg(text).arg(p.name).arg(p.code));
    }
    else
    {
        UserLogger::error(QString(tr("Fail to %1 parameter %2(%3)")).arg(text).arg(p.name).arg(p.code));
    }
}

void ParamSet::setWidgetVisibleSlot(int permission)
{
    Q_UNUSED(permission)
}

void ParamSet::modifyParamSlot()
{
    QToolButton* btnModifyParam = (QToolButton*)sender();
    QString paramName = btnModifyParam->whatsThis();

    Parameter p;
    p.name = paramName;
    QList<Parameter> paramList = sqlHelper->selectParameter(p);
    p = paramList[0];
    bdf->sendModifyParameter(p);

    paramModify->show();
}

void ParamSet::deleteParamSlot()
{
    QToolButton* btnDeleteParam = (QToolButton*)sender();
    QString paramName = btnDeleteParam->whatsThis();
    Parameter p;
    p.name = paramName;
    QList<Parameter> paramList = sqlHelper->selectParameter(p);
    p = paramList[0];
    bdf->sendDeleteParameter(p);
}

void ParamSet::retranslateUiSlot()
{
    ui->retranslateUi(this);
    retranslateTable();
}

void ParamSet::initWidget()
{
    ui->tableWidget->setProperty("noinput",true);//不需要虚拟键盘
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);//单元格不可编辑
    int headerHeight = 47;
    ui->tableWidget->horizontalHeader()->setFixedHeight(headerHeight);
    ui->tableWidget->verticalHeader()->hide();

    if (windowWidth >= 1280) {
        ui->tableWidget->setColumnWidth(0,135);
        ui->tableWidget->setColumnWidth(1,96);
        ui->tableWidget->setColumnWidth(2,90);
        ui->tableWidget->setColumnWidth(3,90);
        ui->tableWidget->setColumnWidth(4,90);
        ui->tableWidget->setColumnWidth(5,120);
        ui->tableWidget->setColumnWidth(6,115);
        ui->tableWidget->setColumnWidth(7,90);
    } else {
        ui->tableWidget->setColumnWidth(0,105);
        ui->tableWidget->setColumnWidth(1,80);
        ui->tableWidget->setColumnWidth(2,66);
        ui->tableWidget->setColumnWidth(3,80);
        ui->tableWidget->setColumnWidth(4,80);
        ui->tableWidget->setColumnWidth(5,100);
        ui->tableWidget->setColumnWidth(6,85);
        ui->tableWidget->setColumnWidth(7,80);
    }
    ui->tableWidget->horizontalHeader()->setStretchLastSection(true);//最后一个单元格扩展

    showAllParametersSlot();

    paramAdd = new ParamAdd();
    paramModify = new ParamModify();
    paramDelete = new ParamDelete();

    if (windowWidth >= 1280) {
        this->setProperty("cssSize", "large");
        paramAdd->setGeometry(0,0,1280,800);
        paramAdd->setProperty("cssSize", "large");
        QToolButton *btnIsOn = paramAdd->findChild<QToolButton *>("btnIsOn");
        btnIsOn->setMaximumWidth(140);
        paramModify->setGeometry(0,0,1280,800);
        paramModify->setProperty("cssSize", "large");
        btnIsOn = paramModify->findChild<QToolButton *>("btnIsOn");
        btnIsOn->setMaximumWidth(140);
        paramDelete->setGeometry(0,0,1280,800);
        paramDelete->setProperty("cssSize", "large");
    }
}

void ParamSet::retranslateTable()
{
    showAllParametersSlot();
}
